using MailKit.Net.Smtp;
using MimeKit;

namespace Project_Schedule.Utilities;

public static class MailHelper
{
    private static string? Address { get; }
    private static string? AuthPwd { get; }
    private static string? Name { get; }
    private static string? Host { get; }
    private static int Port { get; }
    private static bool EnableSsl { get; }

    static MailHelper()
    {
        var section = Assemble_System.Configuration!.GetSection("Mail:Default");
        Address = section["Address"]!;
        AuthPwd = section["AuthPwd"]!;
        Name = section["Name"]!;
        Host = section["Host"]!;
        Port = section["Port"]!.GetInt();
        EnableSsl = section["EnableSsl"]!.GetBool();
    }

    /// <summary>
    /// 发送邮件
    /// </summary>
    /// <param name="title">标题</param>
    /// <param name="content">内容</param>
    /// <param name="list">收件人</param>
    public static void Send(string title, string content, params string[] list)
    {
        var message = new MimeMessage();
        message.From.Add(new MailboxAddress(Name, Address));
        foreach (var item in list)
        {
            message.To.Add(new MailboxAddress("", item));
        }

        message.Subject = title;
        var body = new BodyBuilder
        {
            TextBody = content
        };
        message.Body = body.ToMessageBody();

        // 配置smtp服务地址
        using var client = new SmtpClient();
        client.ServerCertificateValidationCallback =
            (_, _, _, _) => true;
        client.Connect(Host, Port, EnableSsl);
        client.Authenticate(Address, AuthPwd);
        client.Send(message);
        client.Disconnect(true);
    }
}